package com.jiyun.service.impl;

import com.jiyun.entity.Goods;
import com.jiyun.entity.Order;
import com.jiyun.mapper.GoodsMapper;
import com.jiyun.mapper.OrderMapper;
import com.jiyun.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-03-28
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    OrderMapper orderMapper;


    @Override
    @Transactional // 事务，多条sql语句，要么同时成功，要么一起失败，并回滚
    public Integer add(Order order) {
        // 1.扣减库存
        // 2.判断库存是否变为0以下
        // 3.添加订单
        Goods goods = goodsMapper.selectById(order.getGid());
        goods.setId(order.getGid());
        goods.setNum(goods.getNum()-1);
        goodsMapper.updateById(goods);

        if (goods.getNum()<0) {
            throw new RuntimeException("库存异常，终止交易！");
        }

        orderMapper.insert(order);
        return 200;
    }
}
